<template>
  <div class="app-container">

    <el-form-item label="栏目" prop="categoryId">
      <el-select v-model="queryParams.categoryId" placeholder="请选择栏目" clearable>
        <el-option
            v-for="category in categoryOptions"
            :key="category.categoryId"
            :label="category.categoryName"
            :value="category.categoryId"
        />
      </el-select>
    </el-form-item>


    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入标题"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="作者" prop="author">
        <el-input
          v-model="queryParams.author"
          placeholder="请输入作者"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="来源" prop="source">
        <el-select v-model="queryParams.source" placeholder="请选择来源" clearable>
          <el-option label="网络转载" value="0" />
          <el-option label="自制原创" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="是否置顶" prop="isTop">
        <el-select v-model="queryParams.isTop" placeholder="请选择是否置顶" clearable>
          <el-option label="否" value="0" />
          <el-option label="是" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="是否热门" prop="isHot">
        <el-select v-model="queryParams.isHot" placeholder="请选择是否热门" clearable>
          <el-option label="否" value="0" />
          <el-option label="是" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in content_article_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="发布时间" style="width: 308px">
        <el-date-picker
          v-model="daterangePublishTime"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="更新时间" style="width: 308px">
        <el-date-picker
          v-model="daterangeUpdateTime"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="评论数" prop="commentNum">
        <el-input
          v-model="queryParams.commentNum"
          placeholder="请输入评论数"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="点赞数" prop="likeNum">
        <el-input
          v-model="queryParams.likeNum"
          placeholder="请输入点赞数"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['article:article:add']"
        >添加资讯</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['article:article:remove']"
        >批量删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 资讯卡片列表 -->
    <div class="article-card-list">
      <div
          v-for="article in articleList"
          :key="article.articleId"
          class="article-card"
          :class="{ 'article-card-top': article.isTop === '1' }"
      >
        <div class="article-checkbox">
          <el-checkbox
              v-model="article.checked"
              @change="handleCardSelectionChange(article)"
          />
        </div>
        <div class="article-content">
          <div class="article-left">
            <image-preview
                :src="article.coverImage"
                :width="120"
                :height="80"
                class="article-cover"
            />
          </div>
          <div class="article-right">
            <div class="article-header">
              <h3 class="article-title">{{ article.title }}</h3>
              <div class="article-status-tags">
                <el-tag
                    :type="getStatusTagType(article.status)"
                    size="small"
                >
                  {{ getStatusLabel(article.status) }}
                </el-tag>
                <el-tag v-if="article.isTop === '1'" type="warning" size="small">置顶</el-tag>
                <el-tag v-if="article.isHot === '1'" type="danger" size="small">热门</el-tag>
              </div>
            </div>
            <div class="article-meta">
              <span class="article-author">作者：{{ article.author }}</span>
              <span class="article-time">发布时间：{{ parseTime(article.publishTime, '{y}-{m}-{d}') }}</span>
            </div>
            <div class="article-stats">
              <span class="article-stat-item">
                <el-icon><Star /></el-icon>
                点赞：{{ article.likeNum || 0 }}
              </span>
              <span class="article-stat-item">
                <el-icon><ChatDotRound /></el-icon>
                评论：{{ article.commentNum || 0 }}
              </span>
            </div>
          </div>
        </div>
        <div class="article-actions">
          <el-button
              link
              type="primary"
              @click="handleToggleTop(article)"
              v-hasPermi="['article:article:edit']"
          >
            {{ article.isTop === '1' ? '取消置顶' : '置顶' }}
          </el-button>
          <el-button
              link
              type="primary"
              @click="handleUpdate(article)"
              v-hasPermi="['article:article:edit']"
          >
            编辑
          </el-button>
          <el-button
              link
              type="warning"
              @click="handleToggleStatus(article)"
              v-hasPermi="['article:article:edit']"
              :disabled="!canToggleStatus(article.status)"
          >
            {{ getToggleStatusLabel(article.status) }}
          </el-button>
          <el-button
              link
              type="danger"
              @click="handleDelete(article)"
              v-hasPermi="['article:article:remove']"
          >
            删除
          </el-button>
        </div>
      </div>
    </div>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改资讯管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="articleRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="栏目" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择栏目" style="width: 100%">
            <el-option
                v-for="category in categoryOptions"
                :key="category.categoryId"
                :label="category.categoryName"
                :value="category.categoryId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="封面图" prop="coverImage">
          <image-upload v-model="form.coverImage"/>
        </el-form-item>
        <el-form-item label="内容">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="form.author" placeholder="请输入作者" />
        </el-form-item>
        <el-form-item label="来源" prop="source">
          <el-radio-group v-model="form.source">
            <el-radio label="0">网络转载</el-radio>
            <el-radio label="1">自制原创</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否置顶" prop="isTop">
          <el-radio-group v-model="form.isTop">
            <el-radio label="0">否</el-radio>
            <el-radio label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否热门" prop="isHot">
          <el-radio-group v-model="form.isHot">
            <el-radio label="0">否</el-radio>
            <el-radio label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 移除状态选择 -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handlePublish">发布</el-button>
          <el-button type="warning" @click="handleSaveDraft">存草稿</el-button>
          <el-button @click="cancel">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Article">
import { listArticle, getArticle, delArticle, addArticle, updateArticle, getCategories, toggleTop, toggleStatus } from "@/api/article/article"
import { Star, ChatDotRound } from '@element-plus/icons-vue'


const { proxy } = getCurrentInstance()
const { sys_common_status, content_article_status } = proxy.useDict('sys_common_status', 'content_article_status')

const articleList = ref([])
const categoryOptions = ref([]) // 新增栏目选项
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const daterangePublishTime = ref([])
const daterangeUpdateTime = ref([])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    categoryId: null,
    title: null,
    author: null,
    source: null,
    isTop: null,
    isHot: null,
    status: null,
    publishTime: null,
    updateTime: null,
    commentNum: null,
    likeNum: null
  },
  rules: {
    categoryId: [
      { required: true, message: "栏目ID不能为空", trigger: "change" }
    ],
    title: [
      { required: true, message: "标题不能为空", trigger: "blur" }
    ],
    content: [
      { required: true, message: "内容不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询资讯管理列表 */
function getList() {
  loading.value = true
  queryParams.value.params = {}
  if (null != daterangePublishTime && '' != daterangePublishTime) {
    queryParams.value.params["beginPublishTime"] = daterangePublishTime.value[0]
    queryParams.value.params["endPublishTime"] = daterangePublishTime.value[1]
  }
  if (null != daterangeUpdateTime && '' != daterangeUpdateTime) {
    queryParams.value.params["beginUpdateTime"] = daterangeUpdateTime.value[0]
    queryParams.value.params["endUpdateTime"] = daterangeUpdateTime.value[1]
  }
  listArticle(queryParams.value).then(response => {
    articleList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

/** 查询栏目列表 */
function getCategoryList() {
  getCategories().then(response => {
    categoryOptions.value = response.data
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    articleId: null,
    categoryId: null,
    title: null,
    coverImage: null,
    content: null,
    author: null,
    source: null,
    isTop: null,
    isHot: null,
    status: null,
    publishTime: null,
    updateTime: null,
    commentNum: null,
    likeNum: null
  }
  proxy.resetForm("articleRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  daterangePublishTime.value = []
  daterangeUpdateTime.value = []
  proxy.resetForm("queryRef")
  handleQuery()
}

/** 卡片选择变化 */
function handleCardSelectionChange(article) {
  // 更新选中ID数组
  const selectedArticles = articleList.value.filter(item => item.checked)
  ids.value = selectedArticles.map(item => item.articleId)
  multiple.value = selectedArticles.length === 0
}


/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加资讯管理"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _articleId = row.articleId || ids.value
  getArticle(_articleId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改资讯管理"
  })
}


/** 发布操作 */
function handlePublish() {
  proxy.$refs["articleRef"].validate(valid => {
    if (valid) {
      // 设置状态为待审核(0)
      form.value.status = "0"
      submitForm()
    }
  })
}

/** 存草稿操作 */
function handleSaveDraft() {
  proxy.$refs["articleRef"].validate(valid => {
    if (valid) {
      // 设置状态为草稿(3)
      form.value.status = "3"
      submitForm()
    }
  })
}
/** 提交表单 */
function submitForm() {
  if (form.value.articleId != null) {
    updateArticle(form.value).then(response => {
      proxy.$modal.msgSuccess("修改成功")
      open.value = false
      getList()
    })
  } else {
    addArticle(form.value).then(response => {
      proxy.$modal.msgSuccess("新增成功")
      open.value = false
      getList()
    })
  }
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _articleIds = row.articleId || ids.value
  proxy.$modal.confirm('是否确认删除资讯管理编号为"' + _articleIds + '"的数据项？').then(function() {
    return delArticle(_articleIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

// 修改置顶/取消置顶操作
function handleToggleTop(article) {
  const action = article.isTop === '1' ? '取消置顶' : '置顶'
  proxy.$modal.confirm(`确定要${action}该资讯吗？`).then(function() {
    return toggleTop(article.articleId)
  }).then(response => {
    proxy.$modal.msgSuccess(`${action}成功`)
    // 更新本地数据，避免重新请求整个列表
    article.isTop = article.isTop === '1' ? '0' : '1'
  }).catch(() => {})
}

// 修改发布/下架操作
function handleToggleStatus(article) {
  const action = getToggleStatusLabel(article.status)
  proxy.$modal.confirm(`确定要${action}该资讯吗？`).then(function() {
    return toggleStatus(article.articleId)
  }).then(response => {
    proxy.$modal.msgSuccess("操作成功")
    // 更新本地状态
    const newStatus = getNewStatusAfterToggle(article.status)
    article.status = newStatus
  }).catch(() => {})
}

// 添加获取切换后状态的方法
function getNewStatusAfterToggle(currentStatus) {
  switch (currentStatus) {
    case '1': // 已发布 -> 下架
      return '4'
    case '3': // 草稿 -> 待审核
    case '4': // 已下架 -> 待审核
      return '0'
    default:
      return currentStatus
  }
}
/** 获取状态标签类型 */
function getStatusTagType(status) {
  const typeMap = {
    '0': 'info',    // 待审核
    '1': 'success', // 已发布
    '2': 'danger',  // 未通过
    '3': 'warning', // 草稿
    '4': 'info'     // 已下架
  }
  return typeMap[status] || 'info'
}

/** 获取状态切换按钮文本 */
function getToggleStatusLabel(status) {
  const labelMap = {
    '1': '下架',      // 已发布 -> 下架
    '3': '发布',      // 草稿 -> 发布（实际是提交审核）
    '4': '重新提交'   // 已下架 -> 重新提交
  }
  return labelMap[status] || '操作'
}

/** 检查是否可以切换状态 */
function canToggleStatus(status) {
  return ['1', '3', '4'].includes(status)
}

/** 获取状态显示文本 */
function getStatusLabel(status) {
  const statusMap = {
    '0': '待审核',
    '1': '已发布',
    '2': '未通过',
    '3': '草稿',
    '4': '已下架'
  }
  return statusMap[status] || status
}

getCategoryList()
getList()
</script>

<style scoped>
.article-card-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.article-card {
  display: flex;
  align-items: center;
  padding: 16px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background: #fff;
  transition: all 0.3s;
  position: relative;
}

.article-card:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.article-card-top {
  border-left: 4px solid #e6a23c;
  background: #fdf6ec;
}

.article-checkbox {
  margin-right: 16px;
}

.article-content {
  display: flex;
  flex: 1;
  gap: 16px;
}

.article-left {
  flex-shrink: 0;
}

.article-cover {
  border-radius: 4px;
  object-fit: cover;
}

.article-right {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.article-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 12px;
}

.article-title {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  flex: 1;
}

.article-status-tags {
  display: flex;
  gap: 8px;
  flex-shrink: 0;
}

.article-meta {
  display: flex;
  gap: 24px;
  font-size: 14px;
  color: #606266;
}

.article-stats {
  display: flex;
  gap: 16px;
  font-size: 14px;
  color: #909399;
}

.article-stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.article-actions {
  display: flex;
  gap: 16px;
  flex-shrink: 0;
}
</style>